package com.cyrilmottier.android.gdcatalog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.cyrilmottier.android.gdcatalog.util.Constants;
import com.cyrilmottier.android.gdcatalog.util.UploadUtil;

public class CameraActivity extends Activity {

	private ImageView preview;
	private Bitmap myBitmap;

	private String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator + "images"
			+ File.separator + "IMG.jpg";

	private String imagePath;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera);
		preview = (ImageView) this.findViewById(R.id.imageView);
		Button btn = (Button) findViewById(R.id.btn_open);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(getImageByCamera, 1);
			}
		});

		Button btnUpload = (Button) findViewById(R.id.btn_upload);
		btnUpload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File imageFile = new File(imagePath);
				if (imageFile != null) {
					String request = UploadUtil.uploadFile(imageFile, Constants.REQUEST_URL);
					Toast.makeText(getApplicationContext(), request, 0).show();
				}
			}
		});

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
				.detectNetwork().penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
				.detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			super.onActivityResult(requestCode, resultCode, data);
			Bundle extras = data.getExtras();
			myBitmap = (Bitmap) extras.get("data");
			preview.setImageBitmap(myBitmap);
			// 保存到SD卡上

			// FileOutputStream out = new FileOutputStream(imagePath);
			System.out.println("SD_CARD_TEMP_DIR : " + SD_CARD_TEMP_DIR);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

			byte[] photoBytes = baos.toByteArray();

			File aFile = new File(getDatedFName(SD_CARD_TEMP_DIR));

			boolean b;
			if (aFile.exists())
				b = aFile.delete();
			// f.mkdirs();
			aFile.createNewFile(); // need add permission to manifest

			FileOutputStream fos = new FileOutputStream(aFile);
			fos.write(photoBytes);
			fos.close();
			imagePath = aFile.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getDatedFName(String fname) {
		StringBuffer result = new StringBuffer();

		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		String dateSfx = "_" + df.format(new Date());

		int idx = fname.lastIndexOf('.');
		if (idx != -1) {
			result.append(fname.substring(0, idx));
			result.append(dateSfx);
			result.append(fname.substring(idx));
		} else {
			result.append(fname);
			result.append(dateSfx);
		}

		return result.toString();
	}

}